package arp.repository.springdatamongodb;

import java.util.List;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import arp.repository.SimplePersistenceRepository;

public abstract class SimpleMongodbRepository<E, I> extends
		SimplePersistenceRepository<E, I> {

	protected MongoTemplate mongoTemplate;

	protected SimpleMongodbRepository(MongoTemplate mongoTemplate) {
		if (mongoTemplate == null) {
			initAsMock();
		} else {
			this.mongoTemplate = mongoTemplate;
		}
	}

	@Override
	protected void updateImpl(I id, E entity) {
		mongoTemplate.save(entity);
	}

	@Override
	protected E findByIdImpl(I id) {
		return mongoTemplate.findById(id, getEntityClass());
	}

	protected abstract Class<E> getEntityClass();

	@Override
	protected void saveImpl(I id, E entity) {
		mongoTemplate.save(entity);
	}

	@Override
	protected void removeImpl(I id) {
		E entity = mongoTemplate.findById(id, getEntityClass());
		if (entity == null) {
			return;
		}
		mongoTemplate.remove(entity);
	}

	public List<E> findAll() {
		return mongoTemplate.findAll(getEntityClass());
	}

	public I findMaxId() {
		if (mongoTemplate == null) {
			return null;
		}
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "_id"));
		query.limit(1);
		E maxEtt = mongoTemplate.findOne(query, getEntityClass());
		if (maxEtt == null) {
			return null;
		}
		return getId(maxEtt);
	}

	public List<E> findAllByField(String fieldName, Object fieldValue) {
		Query query = new Query();
		query.addCriteria(Criteria.where(fieldName).is(fieldValue));
		return mongoTemplate.find(query, getEntityClass());
	}

}
